/* -------------------------------------------------------------------------
 *
 * auth_delay.c
 *
 * Copyright (c) 2010-2022, PostgreSQL Global Development Group
 *
 * IDENTIFICATION
 *		contrib/auth_delay/auth_delay.c
 *
 * -------------------------------------------------------------------------
 */
#include "postgres.h"

#include <limits.h>

#include "libpq/auth.h"
#include "port.h"
#include "utils/guc.h"
#include "utils/timestamp.h"

PG_MODULE_MAGIC;

void		_PG_init(void);

/* GUC 变量 */
static int	auth_delay_milliseconds;

/* 原始钩子 */
static ClientAuthentication_hook_type original_client_auth_hook = NULL;

/*
 * 检查身份验证
 */
static void fc_auth_delay_checks(Port *fc_port, int fc_status)
{
	/*
	 * 任何其他使用 ClientAuthentication_hook 的插件。
	 */
	if (original_client_auth_hook)
		original_client_auth_hook(fc_port, fc_status);

	/*
	 * 如果身份验证失败，则注入短暂延迟。
	 */
	if (fc_status != STATUS_OK)
	{
		pg_usleep(1000L * auth_delay_milliseconds);
	}
}

/*
 * 模块加载回调
 */
void _PG_init(void)
{
	/* 定义自定义 GUC 变量 */
	DefineCustomIntVariable("auth_delay.milliseconds",
							"Milliseconds to delay before reporting authentication failure",
							NULL,
							&auth_delay_milliseconds,
							0,
							0, INT_MAX / 1000,
							PGC_SIGHUP,
							GUC_UNIT_MS,
							NULL,
							NULL,
							NULL);

	MarkGUCPrefixReserved("auth_delay");

	/* 安装钩子 */
	original_client_auth_hook = ClientAuthentication_hook;
	ClientAuthentication_hook = fc_auth_delay_checks;
}
